import requests
import os

BASE_URL = "http://localhost:3001/api/v1"
API_KEY = "Bearer Z27C9VS-AZZMGRE-KY8Z7T8-6XY3TQS"

MIME_TYPES = {
    '.pdf': 'application/pdf',
    '.doc': 'application/msword',
    '.docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
    '.xls': 'application/vnd.ms-excel',
    '.xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    '.txt': 'text/plain'}


def upload_file(file_path, workspaceSlug):
    """    上传文档到工作区的文档库    """
    url = f"{BASE_URL}/document/upload"
    headers = {"Accept": "application/json",
               "Authorization": API_KEY,
               "Content-Type": "multipart/form-data"
               }

    fext = os.path.splitext(file_path)[1].lower()
    fname = os.path.basename(file_path)
    MIME_TYPE = MIME_TYPES.get(fext, 'application/octet-stream')  # 默认返回 'application/octet-stream'

    with open(file_path, 'rb') as frb:
        files = {'file': (file_path.encode('utf-8'), frb, MIME_TYPE)}
        response = requests.post(url, headers=headers, files=files)
        print(response.text)

    # files = {'file': (file_path.encode('utf-8'), open(file_path, 'rb'))}
    # # data = {"workspaceSlug": workspaceSlug}
    #
    # response = requests.post(url, headers=headers, files=files)
    # print(response.text)
    # upload_result = response.json().get('success')
    # location = response.json().get('documents')[0]['location']
    # print(f"upload_result: {upload_result}\nlocation: {location}")
    # return upload_result, location



if __name__ == "__main__":
    files_list = ['E:\lihz\\10-Library\\08_webServer\k_khlc2025\\test-表格、JSON、公式、坏json - 副本.docx']
    workspaceSlug = "18133612"
    upload_result, location = upload_file(files_list[0], workspaceSlug)
    print(upload_result, location)
